﻿using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Text;

namespace Util
{
   public class JsonHelper
    {
        /// <summary>
        /// Json 序列化配置
        /// </summary>
        public static readonly JsonSerializerSettings JsonSerializerSettings = new JsonSerializerSettings
        {
            Converters = new List<JsonConverter>(){new IsoDateTimeConverter{ DateTimeFormat = "yyyy'-'MM'-'dd' 'HH':'mm':'ss" }},
            NullValueHandling = NullValueHandling.Include,
            ContractResolver = new CamelCasePropertyNamesContractResolver(),
            ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
            PreserveReferencesHandling = PreserveReferencesHandling.None,
        };

        /// <summary>
        /// 转换对象为json格式字符串
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="loadSetting">加载设置</param>
        /// <returns></returns>
        public static string ToJson(object obj, bool loadSetting = true)
        {
            return loadSetting
                // 设置参数为Formatting.Indented可输出格式化后的json
                ? JsonConvert.SerializeObject(obj, Formatting.None, JsonSerializerSettings)
                : JsonConvert.SerializeObject(obj, Formatting.None);
        }
    }
}
